<template>
  <div class="pdf-viewer-container">
    <el-card class="pdf-card">
      <template #header>
        <div class="pdf-header">
          <h3>PDF 预览器</h3>
          <div class="pdf-actions">
            <el-button 
              type="primary" 
              @click="openFileDialog"
              :icon="Upload"
            >
              选择PDF文件
            </el-button>
            <el-button 
              v-if="pdfUrl"
              type="success" 
              @click="downloadPdf"
              :icon="Download"
            >
              下载PDF
            </el-button>
            <el-button 
              v-if="pdfUrl"
              type="info" 
              @click="printPdf"
              :icon="Printer"
            >
              打印PDF
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- PDF文件选择区域 -->
      <div v-if="!pdfUrl" class="file-select-area">
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="false"
          accept=".pdf"
          :on-change="handleFileChange"
          drag
        >
          <div class="upload-content">
            <el-icon class="upload-icon"><Upload /></el-icon>
            <div class="upload-text">
              <p>点击或拖拽PDF文件到此处</p>
              <p class="upload-hint">支持PDF格式文件</p>
            </div>
          </div>
        </el-upload>
      </div>
      
      <!-- PDF预览区域 -->
      <div v-if="pdfUrl" class="pdf-preview-area">
        <!-- 工具栏 -->
        <div class="pdf-toolbar">
          <div class="toolbar-left">
            <el-button-group>
              <el-button 
                :disabled="currentPage <= 1"
                @click="previousPage"
                :icon="ArrowLeft"
              >
                上一页
              </el-button>
              <el-button 
                :disabled="currentPage >= totalPages"
                @click="nextPage"
                :icon="ArrowRight"
              >
                下一页
              </el-button>
            </el-button-group>
            
            <div class="page-info">
              <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
            </div>
          </div>
          
          <div class="toolbar-right">
            <el-button-group>
              <el-button 
                @click="zoomOut"
                :icon="ZoomOut"
                :disabled="scale <= 0.5"
              >
                缩小
              </el-button>
              <el-button @click="resetZoom">
                {{ Math.round(scale * 100) }}%
              </el-button>
              <el-button 
                @click="zoomIn"
                :icon="ZoomIn"
                :disabled="scale >= 3"
              >
                放大
              </el-button>
            </el-button-group>
            
            <el-button 
              @click="toggleFullscreen"
              :icon="FullScreen"
            >
              {{ isFullscreen ? '退出全屏' : '全屏' }}
            </el-button>
            
            <el-button 
              @click="showDebug = !showDebug"
              :type="showDebug ? 'primary' : 'default'"
            >
              {{ showDebug ? '隐藏调试' : '显示调试' }}
            </el-button>
          </div>
        </div>
        
        <!-- PDF内容区域 -->
        <div class="pdf-content" ref="pdfContentRef">
          <div v-if="loading" class="loading-container">
            <el-icon class="loading-icon"><Loading /></el-icon>
            <p>正在加载PDF...</p>
          </div>
          
          <div v-else-if="error" class="error-container">
            <el-icon class="error-icon"><Warning /></el-icon>
            <p>{{ error }}</p>
            <el-button @click="retryLoad">重试</el-button>
          </div>
          
          <div v-else class="pdf-pages">
            <div class="debug-info">
              调试信息: loading={{ loading }}, error={{ error }}, visiblePages={{ visiblePages }}
            </div>
            
            <!-- 强制显示一个测试canvas -->
            <div class="pdf-page test-page">
              <canvas 
                id="test-canvas"
                class="page-canvas"
                data-page="test"
              ></canvas>
              <div class="page-debug">测试Canvas</div>
            </div>
            
            <div 
              v-for="pageNum in visiblePages" 
              :key="pageNum"
              class="pdf-page"
              :style="{ transform: `scale(${scale})` }"
            >
              <canvas 
                :id="`pdf-canvas-${pageNum}`"
                class="page-canvas"
                :data-page="pageNum"
              ></canvas>
              <div class="page-debug">
                页面 {{ pageNum }} - 缩放: {{ Math.round(scale * 100) }}%
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 文件信息对话框 -->
    <el-dialog
      v-model="showFileInfo"
      title="PDF文件信息"
      width="500px"
    >
      <div class="file-info">
        <p><strong>文件名：</strong>{{ fileInfo.name }}</p>
        <p><strong>文件大小：</strong>{{ formatFileSize(fileInfo.size) }}</p>
        <p><strong>页数：</strong>{{ fileInfo.pages }} 页</p>
        <p><strong>上传时间：</strong>{{ fileInfo.uploadTime }}</p>
      </div>
      <template #footer>
        <el-button @click="showFileInfo = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Upload,
  Download,
  Printer,
  ArrowLeft,
  ArrowRight,
  ZoomIn,
  ZoomOut,
  FullScreen,
  Loading,
  Warning
} from '@element-plus/icons-vue'
// 使用CDN版本的PDF.js避免兼容性问题
const pdfjsLib = (window as any).pdfjsLib

// 配置PDF.js - 使用CDN worker
if (pdfjsLib) {
  pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js'
}

// 响应式数据
const pdfUrl = ref<string | null>(null)
const pdfDocument = ref<any>(null)
const currentPage = ref(1)
const totalPages = ref(0)
const scale = ref(1)
const loading = ref(false)
const error = ref('')
const isFullscreen = ref(false)
const showFileInfo = ref(false)
const showDebug = ref(false)
const pdfContentRef = ref<HTMLElement>()
const uploadRef = ref()

// 文件信息
const fileInfo = ref({
  name: '',
  size: 0,
  pages: 0,
  uploadTime: ''
})

// 获取canvas元素
const getCanvas = (pageNum: number): HTMLCanvasElement | null => {
  const canvasId = `pdf-canvas-${pageNum}`
  const canvas = document.getElementById(canvasId) as HTMLCanvasElement
  console.log('获取canvas:', pageNum, 'ID:', canvasId, '元素:', canvas)
  
  // 检查测试canvas
  const testCanvas = document.getElementById('test-canvas')
  console.log('测试canvas:', testCanvas)
  
  // 如果没找到，列出所有canvas元素
  if (!canvas) {
    const allCanvases = document.querySelectorAll('canvas')
    console.log('所有canvas元素:', Array.from(allCanvases).map(c => c.id))
  }
  
  return canvas
}

// 可见页面范围
const visiblePages = ref<number[]>([])

// 处理文件选择
const handleFileChange = (file: any) => {
  if (file.raw && file.raw.type === 'application/pdf') {
    const url = URL.createObjectURL(file.raw)
    loadPdf(url, file.raw)
  } else {
    ElMessage.error('请选择PDF文件')
  }
}

// 打开文件选择对话框
const openFileDialog = () => {
  uploadRef.value?.$el.querySelector('input')?.click()
}

// 加载PDF
const loadPdf = async (url: string, file: File) => {
  try {
    console.log('开始加载PDF:', file.name)
    loading.value = true
    error.value = ''
    
    // 检查PDF.js是否加载
    if (!pdfjsLib) {
      throw new Error('PDF.js未加载，请刷新页面重试')
    }
    
    // 设置文件信息
    fileInfo.value = {
      name: file.name,
      size: file.size,
      pages: 0,
      uploadTime: new Date().toLocaleString()
    }
    
    // 加载PDF文档
    const loadingTask = pdfjsLib.getDocument(url)
    
    pdfDocument.value = await loadingTask.promise
    totalPages.value = pdfDocument.value.numPages
    fileInfo.value.pages = totalPages.value
    
    console.log('PDF文档加载完成:', {
      totalPages: totalPages.value,
      pdfUrl: url
    })
    
    pdfUrl.value = url
    currentPage.value = 1
    
    console.log('PDF加载完成，设置状态:', {
      loading: loading.value,
      error: error.value,
      pdfUrl: pdfUrl.value,
      totalPages: totalPages.value,
      currentPage: currentPage.value
    })
    
    // 渲染页面
    console.log('准备调用renderPages')
    await renderPages()
    console.log('renderPages调用完成')
    
    ElMessage.success('PDF加载成功')
  } catch (err) {
    console.error('PDF加载失败:', err)
    error.value = 'PDF加载失败：' + (err as Error).message
    ElMessage.error('PDF加载失败')
  } finally {
    loading.value = false
    console.log('PDF加载完成，loading设为false，最终状态:', {
      loading: loading.value,
      error: error.value,
      pdfUrl: pdfUrl.value
    })
  }
}

// 渲染页面
const renderPages = async () => {
  console.log('RENDER_PAGES_START')
  
  if (!pdfDocument.value) {
    console.log('NO_PDF_DOCUMENT')
    return
  }
  
  visiblePages.value = [1]
  console.log('SET_VISIBLE_PAGES:', visiblePages.value)
  
  await nextTick()
  console.log('NEXT_TICK_DONE')
  
  await new Promise(resolve => setTimeout(resolve, 1000))
  console.log('WAIT_1000MS_DONE')
  
  const allCanvases = document.querySelectorAll('canvas')
  console.log('ALL_CANVASES:', Array.from(allCanvases).map(c => c.id))
  
  const pdfPages = document.querySelector('.pdf-pages')
  console.log('PDF_PAGES_ELEMENT:', pdfPages)
  
  console.log('CURRENT_VISIBLE_PAGES:', visiblePages.value)
  
  console.log('START_RENDER_PAGE_1')
  await renderPage(1)
  console.log('RENDER_PAGES_END')
}

// 渲染单个页面
const renderPage = async (pageNum: number) => {
  console.log(`RENDER_PAGE_START_${pageNum}`)
  
  if (!pdfDocument.value) {
    console.log('NO_PDF_DOCUMENT_IN_RENDER')
    return
  }
  
  const canvas = getCanvas(pageNum)
  console.log('GOT_CANVAS:', canvas)
  
  if (!canvas) {
    console.error('NO_CANVAS_FOUND:', pageNum)
    return
  }
  
  try {
    console.log('开始渲染页面:', pageNum)
    const page = await pdfDocument.value.getPage(pageNum)
    const viewport = page.getViewport({ scale: scale.value })
    
    console.log('页面信息:', {
      pageNum,
      viewport: {
        width: viewport.width,
        height: viewport.height
      },
      scale: scale.value
    })
    
    // 设置canvas尺寸
    const devicePixelRatio = window.devicePixelRatio || 1
    const scaledViewport = page.getViewport({ scale: scale.value * devicePixelRatio })
    
    canvas.width = scaledViewport.width
    canvas.height = scaledViewport.height
    
    // 设置canvas的CSS尺寸
    canvas.style.width = viewport.width + 'px'
    canvas.style.height = viewport.height + 'px'
    
    console.log('Canvas尺寸:', {
      width: canvas.width,
      height: canvas.height,
      styleWidth: canvas.style.width,
      styleHeight: canvas.style.height
    })
    
    const context = canvas.getContext('2d')
    if (!context) {
      console.error('无法获取2D上下文')
      return
    }
    
    // 缩放context以匹配设备像素比
    context.scale(devicePixelRatio, devicePixelRatio)
    
    const renderContext = {
      canvasContext: context,
      viewport: viewport
    }
    
    await page.render(renderContext).promise
    console.log('页面渲染完成:', pageNum)
  } catch (err) {
    console.error('渲染页面失败:', err)
    error.value = '页面渲染失败: ' + (err as Error).message
  }
}

// 上一页
const previousPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    renderPages()
  }
}

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    renderPages()
  }
}

// 放大
const zoomIn = () => {
  if (scale.value < 3) {
    scale.value = Math.min(3, scale.value + 0.25)
    renderPages()
  }
}

// 缩小
const zoomOut = () => {
  if (scale.value > 0.5) {
    scale.value = Math.max(0.5, scale.value - 0.25)
    renderPages()
  }
}

// 重置缩放
const resetZoom = () => {
  scale.value = 1
  renderPages()
}

// 切换全屏
const toggleFullscreen = () => {
  if (!isFullscreen.value) {
    if (pdfContentRef.value?.requestFullscreen) {
      pdfContentRef.value.requestFullscreen()
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen()
    }
  }
  isFullscreen.value = !isFullscreen.value
}

// 下载PDF
const downloadPdf = () => {
  if (pdfUrl.value) {
    const link = document.createElement('a')
    link.href = pdfUrl.value
    link.download = fileInfo.value.name || 'document.pdf'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success('PDF下载开始')
  }
}

// 打印PDF
const printPdf = () => {
  if (pdfUrl.value) {
    const printWindow = window.open(pdfUrl.value, '_blank')
    if (printWindow) {
      printWindow.onload = () => {
        printWindow.print()
      }
    }
  }
}

// 重试加载
const retryLoad = () => {
  if (pdfUrl.value) {
    loadPdf(pdfUrl.value, new File([], fileInfo.value.name))
  }
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 监听全屏变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement
}

// 组件挂载
onMounted(() => {
  document.addEventListener('fullscreenchange', handleFullscreenChange)
})

// 组件卸载
onUnmounted(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  if (pdfUrl.value) {
    URL.revokeObjectURL(pdfUrl.value)
  }
})
</script>

<style scoped>
.pdf-viewer-container {
  max-width: 1200px;
  margin: 0 auto;
}

.pdf-card {
  min-height: 600px;
}

.pdf-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pdf-header h3 {
  margin: 0;
  color: #333;
}

.pdf-actions {
  display: flex;
  gap: 10px;
}

.file-select-area {
  padding: 40px 20px;
  text-align: center;
}

.upload-content {
  padding: 40px;
}

.upload-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 20px;
}

.upload-text p {
  margin: 10px 0;
  color: #666;
}

.upload-hint {
  font-size: 14px;
  color: #999;
}

.pdf-preview-area {
  height: 600px;
  display: flex;
  flex-direction: column;
}

.pdf-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: #f5f5f5;
  border-bottom: 1px solid #e4e7ed;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-info {
  margin-left: 15px;
  color: #666;
  font-size: 14px;
}

.pdf-content {
  flex: 1;
  overflow: auto;
  background: #f9f9f9;
  position: relative;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #666;
}

.loading-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 20px;
  animation: spin 1s linear infinite;
}

.error-icon {
  font-size: 48px;
  color: #f56c6c;
  margin-bottom: 20px;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.pdf-pages {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.pdf-page {
  background: white;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  overflow: hidden;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.page-canvas {
  display: block;
  max-width: 100%;
  height: auto;
  border: 1px solid #ddd;
}

.page-debug {
  position: absolute;
  top: 5px;
  left: 5px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
  z-index: 10;
}

.debug-info {
  background: #f0f0f0;
  border: 1px solid #ccc;
  padding: 10px;
  margin: 10px 0;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
}

.file-info {
  padding: 20px 0;
}

.file-info p {
  margin: 10px 0;
  color: #666;
}

/* 全屏模式样式 */
.pdf-content:fullscreen {
  background: white;
}

.pdf-content:fullscreen .pdf-pages {
  padding: 0;
}

.pdf-content:fullscreen .pdf-page {
  box-shadow: none;
  border-radius: 0;
}
</style>
